import { login, getUserInfo, getStaffInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken() || '',
  userInfo: {}
}

const mutations = {
  setToken(state, data) {
    setToken(data)
    state.token = data
  },
  // 用浅拷贝更新userInfo的值
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 删除用户信息
  removeUserInfo(state) {
    state.userInfo = ''
  },
  // 删除token
  removeToken(state) {
    state.token = ''
    removeToken()
  }
}

const actions = {
  async login(store, data) {
    // 调用登录请求函数
    const res = await login(data)
    console.log('vuex', res)
    store.commit('setToken', res)
    localStorage.setItem('loginTime', Date.now())
  },

  async getUserInfo(store) {
    // 调用获取用户详情函数
    const result = await getUserInfo()
    // const res = await updateStaffInfo(result)
    // console.log(res)
    // 获取员工详细信息
    const detail = await getStaffInfo(result.userId)
    const body = {
      ...result,
      ...detail
    }

    store.commit('setUserInfo', body)
  },

  async logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
